package com.etonenet.etpe.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.etonenet.etpe.entity.SpExtention;
import com.etonenet.etpe.entity.SpInfo;
import com.etonenet.etpe.repository.SpExtentionRepository;
import com.etonenet.etpe.repository.SpInfoRepository;

/**
 * API 用户信息
 * <p>
 * 
 * 基本信息<br>
 * 配额信息
 * 
 * @author wxu
 *
 */
@Service
public class SpService {

	private static Logger logger = LoggerFactory.getLogger(SpService.class);

	/** 当日消耗配额 */
	private Map<Long, Long> rationNumMap;

	private ConcurrentMap<Long, SpInfo> spInfoMap;
	@Autowired
	private SpExtentionRepository spExtentionRepository;
	@Autowired
	private SpInfoRepository spInfoRepository;

	/**
	 * 在数据库中累加值
	 * 
	 * @param spId
	 * @param rationNum
	 */
	public void addRationNum(long spId, long rationNum) {
		spExtentionRepository.addRationNum(spId, rationNum);
	}

	/**
	 * 实时获取当日已消费额度
	 * 
	 * @param spId
	 * @return
	 */
	public long getRationNum(long spId) {
		return rationNumMap.get(spId);
	}

	/**
	 * 重置所有ration num
	 */
	@Scheduled(cron = "0 0 0 * * *")
	public void restRationNumAll() {
		logger.info("restRationNumAll");
		for (Long spId : spInfoMap.keySet()) {
			// 通过数据库同步，并重置；
			// TODO 重置任务执行一次
			long rationNum = 0;
			spExtentionRepository.updateRationNum(spId, rationNum);
			this.rationNumMap.put(spId, rationNum);
		}
		
	}

	/**
	 * 从数据库加载phoneMapApiRationNumMap
	 */
	@Scheduled(fixedRate = 3000)
	public void loadRationNumAll() {
		logger.info("loadRationNumAll");
		for (SpExtention spExtention : spExtentionRepository.findAll()) {
			long spId = spExtention.getSpId();
			this.rationNumMap.put(spId, spExtention.getCostRationNum());
		}
	}

	/**
	 * 从数据库加载spinfo
	 */
	public void loadSpInfoAll() {
		logger.info("loadSpInfoAll");
		for (SpInfo spInfo : spInfoRepository.findAll()) {
			long spId = spInfo.getSpId();
			spInfoMap.put(spId, spInfo);

			// 确保spExtention不为空
			SpExtention spExtention = spExtentionRepository.findOne(spId);
			if (spExtention == null) {
				spExtention = new SpExtention();
				spExtention.setSpId(spId);
				spExtention.setCostRationNum(0);
				spExtentionRepository.save(spExtention);
			}
		}
	}

	@PostConstruct
	public void init() {
		logger.info("init");
		spInfoMap = new ConcurrentHashMap<>();
		rationNumMap = new ConcurrentHashMap<>();
		// 从数据库加载spinfo
		loadSpInfoAll();
		// 从数据库加载phoneMapApiRationNumMap
		loadRationNumAll();
	}

	public SpInfo findBySpId(long spId) {
		return spInfoMap.get(spId);
	}

}
